const { formatTime } = require('../../utils/util.js')
const { checkAuth } = require('../../utils/auth.js')
const { getApiUrl } = require('../../config/config.js')

Page({
  data: {
    type: 'fans', // 默认显示粉丝列表，可选值：fans、follows
    userList: [],
    loading: true,
    page: 1,
    pageSize: 10,
    hasMore: true,
    userId: null
  },

  onLoad(options) {
    // if (!checkAuth()) return
    
    // 获取当前用户ID
    const userInfo = wx.getStorageSync('userInfo')
    const userId = userInfo ? userInfo.id : null
    
    // 设置列表类型和用户ID
    const type = options.type || 'fans'
    this.setData({
      type,
      userId
    })
    
    // 加载数据
    this.loadUserList()
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      page: 1,
      userList: [],
      hasMore: true
    })
    this.loadUserList().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 加载更多
  loadMore() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadUserList()
    }
  },

  // 加载用户列表
  async loadUserList() {
    if (!this.data.userId) return
    
    this.setData({ loading: true })
    
    try {
      const { type, userId, page, pageSize } = this.data
      const url = type === 'fans' 
        ? getApiUrl(`/user/fans/${userId}?page=${page}&size=${pageSize}`)
        : getApiUrl(`/user/follows/${userId}?page=${page}&size=${pageSize}`)
      
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url,
          method: 'GET',
          header: {
            'token': wx.getStorageSync('token')
          },
          success: resolve,
          fail: reject
        })
      })
      
      if (res.data && res.data.code === 200) {
        const newList = res.data.data.map(user => {
          // 格式化时间
          if (user.createTime) {
            user.followTime = formatTime(user.createTime)
          }
          // 截断个人简介
          if (user.biography && user.biography.length > 30) {
            user.biography = user.biography.substring(0, 30) + '...'
          }
          return user
        })
        
        // 更新列表数据
        this.setData({
          userList: page === 1 ? newList : [...this.data.userList, ...newList],
          page: page + 1,
          hasMore: newList.length === pageSize,
          loading: false
        })
      } else {
        // 处理服务器返回的错误
        console.error('Server response error:', res)
        this.setData({ loading: false })
        wx.showToast({
          title: res.data?.message || '获取数据失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('Load user list failed:', error)
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
      this.setData({ loading: false })
    }
  },

  // 切换标签
  switchTab(e) {
    const type = e.currentTarget.dataset.type
    if (type !== this.data.type) {
      this.setData({
        type,
        page: 1,
        userList: [],
        hasMore: true
      })
      this.loadUserList()
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack()
  },

  // 跳转到用户主页
  navigateToUser(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/user/user?id=${id}`
    })
  },

  // 发送私信
  sendMessage(e) {
    const { id, name } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/chat/chat?targetUserId=${id}&targetName=${encodeURIComponent(name || '未知用户')}`
    })
  },

  // 跳转到首页
  navigateToIndex() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },
})
